package com.kt.emall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: e-mall
 * @description: Feign远程调用配置
 * @author: KamTang
 * @create: 2022-02-10 10:44
 **/
@Configuration
public class FeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 1、RequestContextHolder得到开始进来的这个请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest(); // old request
                // 2、同步请求头信息 -- Cookie
                String cookie = request.getHeader("Cookie");
                // 给new quest 同步了 old request的Cookie
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
